package com.pzhuweb.sgblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pzhuweb.sgblog.domain.entity.User;
import com.pzhuweb.sgblog.domain.enums.AppHttpCodeEnum;
import com.pzhuweb.sgblog.exception.SystemException;
import com.pzhuweb.sgblog.mapper.UserMapper;
import com.pzhuweb.sgblog.service.UserService;
import com.pzhuweb.sgblog.domain.utils.BeanCopyUtils;
import com.pzhuweb.sgblog.domain.utils.ResponseResult;
import com.pzhuweb.sgblog.domain.utils.SecurityUtils;
import com.pzhuweb.sgblog.domain.vo.UserInfoVo;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author 鄧浩奇
 * @classname UserServiceImpl
 * @description
 * @since 2023/7/8 16:19
 **/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    public ResponseResult<?> getUserInfo() {
        // 获取用户id
        Long userID = SecurityUtils.getUserID();
        User user = getById(userID);
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        return ResponseResult.okResult(userInfoVo);
    }

    @Override
    public ResponseResult<?> saveInfo(User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,user.getId());
        update(user,queryWrapper);  // 防止恶意全表更新
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult<?> register(User user) {
        if (!StringUtils.hasText(user.getUserName())) {
            throw new SystemException(AppHttpCodeEnum.USERNAME_ISNULL);
        }
        if (!StringUtils.hasText(user.getEmail())) {
            throw new SystemException(AppHttpCodeEnum.EMAIL_ISNULL);
        }
        if (!StringUtils.hasText(user.getNickName())) {
            throw new SystemException(AppHttpCodeEnum.NICKNAME_ISNULL);
        }
        if (!StringUtils.hasText(user.getPassword())) {
            throw new SystemException(AppHttpCodeEnum.PASSWORD_ISNULL);
        }
        // 确保用户名不能重复
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,user.getUserName());
        User one = getOne(queryWrapper);
        if (!Objects.isNull(one)) {
            // 用户名已经存在
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        // 存入数据库
        save(user);
        return ResponseResult.okResult();
    }
}
